package com.geek.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.water.entity.MessageTemplate;
import com.geek.water.mapper.MessageTemplateMapper;
import com.geek.water.service.MessageTemplateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 消息模板服务实现类
 */
@Service
public class MessageTemplateServiceImpl extends ServiceImpl<MessageTemplateMapper, MessageTemplate> implements MessageTemplateService {

    @Override
    public List<MessageTemplate> getTemplatesByType(String type) {
        LambdaQueryWrapper<MessageTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MessageTemplate::getType, type)
                .eq(MessageTemplate::getIsActive, true)
                .orderByAsc(MessageTemplate::getCode);
        return list(wrapper);
    }

    @Override
    public MessageTemplate getTemplateByCodeAndLanguage(String code, String language) {
        LambdaQueryWrapper<MessageTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MessageTemplate::getCode, code)
                .eq(MessageTemplate::getLanguage, language)
                .eq(MessageTemplate::getIsActive, true);
        return getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createTemplate(MessageTemplate template) {
        template.setCreateTime(LocalDateTime.now());
        template.setUpdateTime(LocalDateTime.now());
        template.setCreateBy("admin"); // 这里应该从当前登录用户获取
        template.setUpdateBy("admin");
        return save(template);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTemplate(MessageTemplate template) {
        template.setUpdateTime(LocalDateTime.now());
        template.setUpdateBy("admin"); // 这里应该从当前登录用户获取
        return updateById(template);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleTemplateStatus(Long id, Boolean isActive) {
        MessageTemplate template = new MessageTemplate();
        template.setId(id);
        template.setIsActive(isActive);
        template.setUpdateTime(LocalDateTime.now());
        template.setUpdateBy("admin");
        return updateById(template);
    }
}